package org.example.pool;

import java.util.concurrent.*;

/**
 * 最大线程设置（调优）
 * Runtime.getRuntime().availableProcessors();
 * CPU密集型：大量占用cpu的任务 ==》 CPU数
 * IO 密集型：数据库、网络、文件IO耗时 ==》 2*CPU数
 */
public class MaxSizeSetting {

    public static void main(String[] args) {
        // 创建线程池
        ExecutorService threadPool = new ThreadPoolExecutor(2,
                Runtime.getRuntime().availableProcessors(),
                0L, TimeUnit.MICROSECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        try {
            // max = 8 + 3
            for (int i = 1; i <= 11; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName());
                });
            }
        } finally {
            // 关闭线程池
            threadPool.shutdown();
            System.out.println("CPU处理器数（最大并行线程）：" + Runtime.getRuntime().availableProcessors());
        }
    }
}
